<template>
  <div v-loading.lock="loading" class="base-content">
    <div class="basic-info">
      <el-form
        ref="queryForm"
        :inline="true"
        :model="queryForm"
        label-width="100px"
      >
        <el-form-item :label="dataList.TaskNumber" prop="num">
          <el-input
            v-model="queryForm.num"
            :placeholder="dataList.TaskNumber"
          />
        </el-form-item>
        <el-form-item :label="dataList.Device" prop="deviceNameNum">
          <el-input
            v-model="queryForm.deviceNameNum"
            :placeholder="dataList.EquipNumberOrName"
          />
        </el-form-item>
        <el-form-item
          :label="dataList.CalibrationPersonName"
          prop="calibrationPersonName"
        >
          <el-input
            v-model="queryForm.calibrationPersonName"
            :placeholder="dataList.CalibrationPersonName"
          />
        </el-form-item>
        <el-form-item
          :label="dataList.AssociatedPlan"
          prop="calibrationPlanNameNum"
        >
          <el-input
            v-model="queryForm.calibrationPlanNameNum"
            :placeholder="dataList.AssociatedPlan"
          />
        </el-form-item>
        <el-form-item :label="dataList.Status" prop="status">
          <el-select
            v-model="queryForm.status"
            :placeholder="dataList.Placeholder"
            style="width: 200px"
          >
            <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item :label="dataList.Type" prop="type">
          <el-select
            v-model="queryForm.type"
            :placeholder="dataList.Placeholder"
            style="width: 200px"
          >
            <el-option
              v-for="item in typeOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>

      <div class="base-content-operate">
        <el-button type="primary" @click="onQuery">{{ btn.Query }}</el-button>
        <el-button @click="cancelForm">{{ btn.Reset }}</el-button>
        <el-button icon="el-icon-plus" type="primary" @click="onNew">{{
          btn.Add
        }}</el-button>
        <el-button type="primary" @click="Export">{{ btn.Export }}</el-button>
        <el-button type="primary" @click="editCalibrationPerson">{{
          btn.ModifiedBy
        }}</el-button>
      </div>

      <el-table
        :data="list"
        element-loading-text="Loading"
        fit
        highlight-current-row
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55"> </el-table-column>
        <el-table-column :label="dataList.TaskNumber">
          <template slot-scope="scope">
            <el-link type="primary" @click="toView(scope.row)">
              {{ scope.row.num }}</el-link
            >
          </template>
        </el-table-column>
        <el-table-column :label="dataList.DeviceNumber">
          <template slot-scope="scope">
            {{ scope.row.deviceNum }}
          </template>
        </el-table-column>
        <el-table-column
          :label="
            $i18n.locale === 'en' ? dataList.DeviceEName : dataList.DeviceName
          "
        >
          <template slot-scope="scope">
            {{ scope.row.deviceName }}
          </template>
        </el-table-column>
        <el-table-column :label="dataList.CalibrationPlanDate">
          <template slot-scope="scope">
            {{ formatTime(scope.row.planDate) }}
          </template>
        </el-table-column>
        <el-table-column :label="dataList.DevicePersonResponsibleId">
          <template slot-scope="scope">
            {{ scope.row.personResponsibleName }}
          </template>
        </el-table-column>
        <el-table-column :label="dataList.Type">
          <template slot-scope="scope">
            {{ scope.row.typeName }}
          </template>
        </el-table-column>
        <el-table-column :label="dataList.AssociatedPlan">
          <template slot-scope="scope">
            {{ scope.row.calibrationPlanNum }}
          </template>
        </el-table-column>
        <el-table-column :label="dataList.Status">
          <template slot-scope="scope">
            {{ scope.row.statusName }}
          </template>
        </el-table-column>
        <el-table-column :label="dataList.CalibrationPersonName">
          <template slot-scope="scope">
            {{ scope.row.calibrationPersonName }}
          </template>
        </el-table-column>
        <el-table-column :label="dataList.CalibDate">
          <template slot-scope="scope">
            {{ formatTime(scope.row.calibrationDate) }}
          </template>
        </el-table-column>
        <el-table-column :label="dataList.Operation">
          <template slot-scope="scope">
            <div class="base-table-operation">
              <el-link
                v-if="scope.row.status == 10 || scope.row.status == 40"
                size="mini"
                type="primary"
                @click="handleEdit(scope.row)"
                >{{ btn.Process }}</el-link
              >
              <el-link
                v-if="scope.row.type != 10 && scope.row.status == 10"
                size="mini"
                type="danger"
                @click="handleDelete(scope.row)"
                >{{ btn.Nullify }}</el-link
              >
              <!-- <el-link size="mini" type="primary" @click="handleView(scope.row)"
               >{{btn.Preview}}</el-link
              > -->
            </div>
          </template>
        </el-table-column>
      </el-table>

      <BasePagination
        :total="pagination.total"
        :current-page="pagination.pageIndex"
        :page-count="pagination.total"
        @changePage="changePage"
        @sizeChange="sizeChange"
      />
    </div>

    <DeviceCalibrationTaskDisposeDialog
      v-if="dialogFormDisposeVisible"
      :id.sync="id"
      ref="DeviceCalibrationTaskDisposeDialog"
      :dialog-form-visible.sync="dialogFormDisposeVisible"
    />

    <DeviceCalibrationTaskViewDialog
      v-if="dialogFormViewVisible"
      :id.sync="id"
      ref="DeviceCalibrationTaskViewDialog"
      :dialog-form-visible.sync="dialogFormViewVisible"
    />

    <DeviceCalibrationTaskAddDialog
      v-if="dialogFormVisible"
      ref="DeviceCalibrationTaskAddDialog"
      :dialog-form-visible.sync="dialogFormVisible"
    />
    <DeviceCalibrationTaskExportView
      v-if="dialogFormExportViewVisible"
      :id.sync="id"
      ref="dialogFormExportViewVisible"
      :dialog-form-visible.sync="dialogFormExportViewVisible"
    />

    <el-dialog
      class="base-dialog system-user-dialog"
      :custom-class="'panna-dialog_small'"
      :append-to-body="true"
      :title="dataList.ModifiedBy"
      align="center"
      :close-on-click-modal="false"
      :visible.sync="editAccendantVisible"
    >
      <el-form
        ref="formData"
        label-width="100px"
        :model="formData"
        :rules="formDataRules"
        status-icon
      >
        <el-form-item
          :label="dataList.CalibrationPersonName"
          :label-width="formLabelWidth"
          prop="calibrationPersonId"
          :error="errorMsg.calibrationPersonId"
        >
          <UserDropDownList
            :value="formData.calibrationPersonId"
            :return-objct.sync="returnObjct"
            @input="borrowPersonChange"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer" align="center">
        <el-button type="primary" @click="onSubmit('formData')">{{
          btn.Save
        }}</el-button>
        <el-button @click="cancel">{{ btn.Cancel }}</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  getList,
  ScrapDeviceCalibrationTask,
  updateCalibrationPerson,
} from "../../../api/DeviceCalibrationTask.js";
import DeviceCalibrationTaskAddDialog from "./DeviceCalibrationTaskAddDialog.vue";
import DeviceCalibrationTaskExportView from "./DeviceCalibrationTaskExportView.vue";

import DeviceCalibrationTaskDisposeDialog from "./DeviceCalibrationTaskDisposeDialog.vue";
import UserDropDownList from "../../../components/UserDropDownList.vue";
import DeviceCalibrationTaskViewDialog from "./DeviceCalibrationTaskViewDialog.vue";
import { formatTime } from "../../../utils/time";
import { export_json_to_excel } from "@/vendor/Export2Excel";
import {
  deviceVerificationTaskStatus,
  calibrationType,
} from "../../../utils/const";
export default {
  name: "DeviceCalibrationTaskList",
  components: {
    DeviceCalibrationTaskAddDialog,
    UserDropDownList,
    DeviceCalibrationTaskDisposeDialog,
    DeviceCalibrationTaskViewDialog,
    DeviceCalibrationTaskExportView,
  },
  data() {
    return {
      // tHeader: [
      //   "任务编号",
      //   "设备编号",
      //   "设备名称",
      //   "计划检定/校准时间",
      //   "责任人",
      //   "类型",
      //   "关联计划",
      //   "状态",
      //   "确认人",
      //   "校准日期",
      // ],
      filterVal: [
        "num",
        "deviceNum",
        "deviceName",
        "planDate",
        "personResponsibleName",
        "typeName",
        "calibrationPlanNum",
        "statusName",
        "calibrationPersonName",
        "calibrationDate",
      ],
      id: 0,
      dialogFormExportViewVisible: false,
      formatTime,
      returnObjct: true,
      dialogFormDisposeVisible: false,
      dialogFormViewVisible: false,
      formLabelWidth: "100px",
      loading: true,
      editAccendantVisible: false,
      list: [],
      options: deviceVerificationTaskStatus,
      typeOptions: calibrationType,
      tableData: [],
      formDataRules: {
        calibrationPersonId: [
          {
            required: true,
            trigger: "blur",
            validator: this.Helper.validateFunction,
          },
        ],
      },
      formData: {
        calibrationPersonId: null,
        calibrationPersonName: "",
      },
      errorMsg: {
        calibrationPersonId: null,
      },
      queryForm: {
        num: "",
        deviceNameNum: "",
        calibrationPersonName: "",
        calibrationPlanNameNum: "",
        status: -1,
        type: -1,
        departId: sessionStorage.getItem("currentDepartmentId"),
      },
      dialogFormVisible: false,
      pagination: {
        pageIndex: 1,
        pageSize: 10,
        total: 0,
      },
    };
  },
  computed: {
    btn() {
      return this.$t("ModuleDevice.buttons");
    },
    dataList() {
      return this.$t("ModuleDevice.Device");
    },
  },
  created() {
    this.getList();
  },
  methods: {
    handleView(row) {
      this.id = row.id;
      this.dialogFormExportViewVisible = true;
    },
    export_json_to_excel,
    formatJson(filterVal, jsonData) {
      return jsonData.map((v) =>
        filterVal.map((j) => {
          return v[j];
        })
      );
    },
    Export() {
      getList(this.queryForm, { pageIndex: 1, pageSize: 100000 }).then(
        (res) => {
          var datas = res.data.dataList;
          for (let i = 0; i < datas.length; i++) {
            datas[i].planDate = this.formatTime(datas[i].planDate);
            datas[i].calibrationDate = this.formatTime(
              datas[i].calibrationDate
            );
          }

          var data = this.formatJson(this.filterVal, res.data.dataList);

          const tHeader = [
            this.dataList.TaskNumber,
            this.dataList.DeviceNumber,
            this.dataList.DeviceName,
            this.dataList.CalibrationPlanDate,
            this.dataList.DevicePersonResponsibleId,
            this.dataList.Type,
            this.dataList.AssociatedPlan,
            this.dataList.Status,
            this.dataList.CalibrationPersonName,
            this.dataList.CalibDate,
          ];
          export_json_to_excel({
            header: tHeader, // 表头
            data, // 数据
            filename: this.dataList.CalibTask, // 导出文件名
            autoWidth: true, // 导出宽度自动
            bookType: "xlsx", // 导出后缀
          });
        }
      );
    },
    toView(row) {
      this.id = row.id;
      this.dialogFormViewVisible = true;
    },
    cancel() {
      this.editAccendantVisible = false;
    },
    // 修改维护人
    onSubmit() {
      this.$refs.formData.validate((valid) => {
        if (valid) {
          // this.tableData存的是选中数据
          for (let i = 0; i < this.tableData.length; i++) {
            this.tableData[i].calibrationPersonId =
              this.formData.calibrationPersonId;
            this.tableData[i].calibrationPersonName =
              this.formData.calibrationPersonName;
          }
          updateCalibrationPerson(this.tableData).then((res) => {
            this.getList();
            this.cancel();
          });
        }
      });
    },
    borrowPersonChange(val) {
      this.formData.calibrationPersonId = val.value;
      this.formData.calibrationPersonName = val.label;
    },
    // 修改确认人
    editCalibrationPerson() {
      for (let i = 0; i < this.tableData.length; i++) {
        if (Number(this.tableData[i].status) !== 10) {
          this.$message.warning(
            this.$i18n.t("ModuleDevice.Message.SelectData")
          );
          return false;
        }
      }
      this.editAccendantVisible = true;
    },
    handleSelectionChange(val) {
      this.tableData = val;
    },
    changePage(val) {
      this.pagination.pageIndex = val;
      this.getList();
    },
    sizeChange(val) {
      this.pagination.pageIndex = 1;
      this.pagination.pageSize = val;
      this.getList();
    },
    cancelForm() {
      this.$refs.queryForm.resetFields();
      this.pagination.pageIndex = 1;
      this.getList();
    },
    getList() {
      this.loading = true;
      getList(this.queryForm, this.pagination)
        .then((res) => {
          this.list = res.data.dataList ? res.data.dataList : [];
          this.pagination.total = res.data.total;
          this.loading = false;
        })
        .catch(() => {
          this.loading = false;
        });
    },
    onNew() {
      this.dialogFormVisible = true;
    },
    handleDelete(rowData) {
      this.$confirm(
        this.$i18n.t("ModuleDevice.Message.ConfirmNullify"),
        this.btn.Tips,
        {
          confirmButtonText: this.btn.Confirm,
          cancelButtonText: this.btn.Cancel,
          type: "warning",
          center: true,
        }
      )
        .then(() => {
          ScrapDeviceCalibrationTask({ id: rowData.id })
            .then((res) => {
              this.getList();
            })
            .catch((res) => {});
        })
        .catch(() => {});
    },
    handleEdit(rowData) {
      this.id = rowData.id;
      this.dialogFormDisposeVisible = true;
    },
    onQuery() {
      this.pagination.pageIndex = 1;
      this.getList();
    },
  },
};
</script>
